import { Input, type InputProps } from 'antd'
import { useCallback, useMemo } from 'react'

interface PhoneProps extends Omit<InputProps, 'value'> {
  value?: string
  // onChange?: (value: string) => void
}

export function Phone({
  placeholder = '请输入手机号',
  value,
  onChange,
  ...restProps
}: PhoneProps) {
  const myOnChange = useCallback<NonNullable<InputProps['onChange']>>(
    (event) => {
      const val = event.target.value
      const s1 = val.substring(0, 1)
      const s2 = val.substring(1, 11)
      if (s1 !== '1') {
        event.target.value = ''
      } else {
        event.target.value = s1 + s2.replace(/\D+/g, '')
      }
      onChange?.(event)
    },
    []
  )

  const myValue = useMemo<PhoneProps['value']>(() => {
    if (value && /^\d{0,11}$/.test(value)) {
      return value
    } else {
      return ''
    }
  }, [value])

  return (
    <Input
      placeholder={placeholder}
      maxLength={11}
      value={myValue}
      onChange={myOnChange}
      allowClear
      {...restProps}
    ></Input>
  )
}
